import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken, setUserId, getUserId } from '@/utils/auth'
import Vue from 'vue'
 function _parseLayerUrlParam(url) {
  if (url) {
    const urlArray = url.split('?')
    try {
      var obj = JSON.parse(
        '{"' +
          decodeURIComponent(urlArray[urlArray.length - 1])
            .replace(/"/g, '\\"')
            .replace(/&/g, '","')
            .replace(/=/g, '":"') +
          '"}'
      )
    } catch (e) {
      console.warn('图层URL参数配置不正确，不能正常解析的JSON')
      return {}
    }
    return obj
  }
}

const user = {
  namespaced: true,
  state: {
    id: getUserId(), // 用户ID
    token: getToken(), // Token
    name: '', // 用户名
    avatar: '', // 头像
    roles: [], // 角色、权限
    baseLayers: [], // 基础底图
    xcglBaseLayers:[], //巡查管理基础地图
    baseLayer_3D: [], // 基础底图3D
    eleLayer_3D: '', // 三维高程图层
    dept: '', // 部门,
    baseGroup: [], // 基础地图分组
    subjectData: [], // 二维专题数据
    userSubject: [],
    subjectData_scene: [], // 三维专题数据
    index: 0, // 选中索引
    sceneIndexMap: {},
    bounds: [[0, 0], [0, 0]], // 显示地图边界
    checkedIds: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    setBaseLayers: (state, baseLayers) => {
      state.baseLayers = baseLayers
    },

    setBaseLayer_3D: (state, baseLayers_3D) => {
      state.baseLayer_3D = baseLayers_3D
    },

    setEleLayer_3D: (state, eleLayer_3D) => {
      state.eleLayer_3D = eleLayer_3D
    },

    setDept: (state, dept) => {
      state.dept = dept
    },
    setUserId: (state, id) => {
      state.id = id
    },

    setBaseGroups: (state, groups) => {
      for (let i = 0; i < groups.length; i++) {
        Vue.set(groups[i], 'checked', i === state.index)
      }
      state.baseLayers = groups.length > state.index ? groups[state.index].layers : []
      state.baseGroup = groups;
      state.xcglBaseLayers = groups.length > 1 ? groups[1].layers : []
    },

    setSubjectData: (state, subject) => {
      state.subjectData = subject.filter(i => {
        var cds = subject.filter(item => item.pid == i._id);
        if (i.children.length == 0) {
          i.children = cds;
        } else {
          i.children = i.children.concat(cds);
        }
        return i.level == 0;
      });
    },

    SET_BOUNDS: (state, obj) => {
      state.bounds = obj
    },

    set_userSubject: (state, obj) => {
      state.userSubject = obj
    },

    set_checkedIds: (state, obj) => {
      state.checkedIds = obj
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(response => {
          const data = response.data
          setToken(data.token)
          commit('SET_TOKEN', data.token)
          setUserId(data.userId)
          commit('setUserId', data.userId)

          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo({ uid: state.id }).then(response => {
          const data = response.data
          if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', data.roles)
          } else {
            reject('getInfo: roles must be a non-null array !')
          }
          commit('SET_NAME', data.name) // 名称
          commit('SET_AVATAR', data.avatar) // 头像
          // commit('setBaseLayers', data.baseGroup.length > 0 ? data.baseGroup[0].layers : []) // 底图
          commit('setDept', data.dept) // 部门
          commit('setBaseGroups', data.baseGroup) // 地图切换
          commit('setBaseLayer_3D', data.baseLayer_3D) // 三维底图
          commit('setEleLayer_3D', data.eleLayer_3D) // 三维高程图层
          commit('setSubjectData', data.subjectData)
          commit('SET_BOUNDS', data.bounds)
          commit('set_userSubject', data.userSubject) // 用户
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('setDept', '')
        commit('setUserId', '')
        removeToken()
        resolve()
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  },

  getters: {

    //图层树（无限级目录）
    mapTree(state) {
      var data = state.subjectData;
      return data.filter(i => i.pid === "Map")[0].children || [];
    },


    //图层树（场景目录）
    sceneTree(state) {
      var data = state.subjectData;
      return data.filter(i => i.pid === "Scene")[0].children || [];
    },


    //所有图层
    allLayers(state) {
      var filteredLayers = state.subjectData; //树
      var layers = [];
      var getChildren = (layer)=>{
          if(layer.children){
            layer.children.forEach(i=>{
              if(i.pid){
                getChildren(i);
              }else{
                layers.push(i);
              }
            })
          }
      }
      getChildren(filteredLayers.filter(i => i.pid === "Map")[0])
      return layers;
    },
    
    //基础地图
    allBaseMapLayers(state) {
      var layers = [];
      var groups = state.baseGroup;
      for (let i = 0; i < groups.length; i++) {
        layers = layers.concat(groups[i].layers);
      }
      return layers;
    }
  }
}

export default user
